<?php 

require_once(APPPATH.'controllers/epicentr.php');

class Users extends Epicentr {

	public function Users() {
		parent::Epicentr();
		$this->view_data['maintab'] = '';
	}

	public function index() {
		$this->browse();
	}

	public function browse($start = 0) {
		$this->load->model('usersmodel');
		$this->load->library('pagination');
		$this->load->helper('url');
		
		$this->view_data['page_js'][] = 'jquery.inplace';
		$this->view_data['page_js'][] = 'companies_inplace';
		
		$this->view_data['page_js'][] = 'users';
		
		$limit_per_page = 50;

		$this->load->model('costcentermodel');

		$departments = $this->costcentermodel->getAllCenters();
		
		$department_select = "";
		
		if (!$departments) {
			$departments[0]->id = 0;
			$departments[0]->centertitle = 'No Department';
		}
		
		if ($departments) {
			
			$startdate = date('Y-m-d', strtotime('-7 days') );
			
			$enddate = date('Y-m-d');
			
			$validdays = $this->day_range( $startdate, $enddate);
			
			foreach ($departments as $key => $department) {
				$users = $this->usersmodel->find(array('deleted' => 0, 'costcenterid' => $department->id));
				
				if ($users) {
					foreach ($users as $ukey => $user) {
						$workhours = $this->usersmodel->getUserWorkHours($user->id, $startdate);
	
						$workhoursarray = array();
	
							foreach ($validdays as $dkey => $day) {
	
								if ($workhours) {					
									foreach ($workhours as $hours) {
										if ($hours->dateapplicable == $day) {
											$workhoursarray[$dkey] = $hours->hours_worked;
											break;
										}
									}
								}
	
								if ( !isset($workhoursarray[$dkey]) ) $workhoursarray[$dkey] = 0;
							}
					
						$chart = "http://chart.apis.google.com/chart?chs=100x20&chds=0,8&cht=ls&chco=0077CC&chm=B,E6F2FA,0,0,0&chls=1,0,0&chd=t:".implode(',', $workhoursarray)."&chco=c6d9fd&chf=bg,s,00000000";
					
						$users[$ukey]->spikechart = $chart;
					}
				}
				
				$departments[$key]->users = $users;
				
				if ($key > 0) $department_select .= ',';
				$department_select .= $department->centertitle.":".$department->id;
			}
		}
		
		$mycompany = $this->companiesmodel->getMyCompany();
		
		$this->view_data['mycompany'] = $mycompany;
		
		$this->view_data['departments'] = $departments;
		$this->view_data['department_select'] = $department_select;

		$this->layout->buildPage('/users/usersgrid', $this->view_data);
	}

	public function add() {
		$submit = $this->input->post('Submit');

		//presubmit checks
		if ( $submit != false ) {
			$this->load->model('usersmodel');
			$data['user'] = $this->_get_form_values('add');
			
			if ( !$this->usersmodel->find( array('emailaddress' => $data['user']->emailaddress)) === false ) {
				//username in use
				$submit = false;
				$this->view_data['flasherror'] = 'This emailaddress already has an account associated with it.';
			}
		}
		
		if ( $submit != false ) {
			//encrypt password
			$data['user']->password = md5($data['user']->password);
			$newid = $this->usersmodel->add((array)$data['user']);
			
			$this->db_session->set_flashdata('newid', $newid);
			$this->db_session->set_flashdata('flashmessage', 'Your new user was created successfully.');
			
			redirect('/users/', 'location');
		} else {
			$this->view_data['user'] = $this->_clear_form();
			
			$this->view_data['action'] = 'add';
			$this->layout->buildPage('/users/usersdetails', $this->view_data);
		}
	}
	
	public function adddepartment() {
		$this->load->model('costcentermodel');
		
		$data = null;
		
		$data->centertitle = $this->input->post('centertitle');
		$data->hourlyrate = $this->input->post('hourlyrate');
		
		$newid = $this->costcentermodel->addDepartment($data);
		
		$this->db_session->set_flashdata('newid', $newid);
		$this->db_session->set_flashdata('flashmessage', 'The new department '.$data->centertitle.' was added.');
			 
		redirect('/yourcompany/', 'location');
	}

	public function view($userid) {
		$this->load->model('usersmodel');
		
		$user = $this->usersmodel->retrieve_by_pkey($userid);
		
		if ($user) {
			$startdate = date('Y-m-d', strtotime('-7 days') );
			$enddate = date('Y-m-d');

			$validdays = $this->day_range( $startdate, $enddate);
			
			$workhours = $this->usersmodel->getUserWorkHours($user->id, $startdate);

			$workhoursarray = array();

			$daylabels = array();

			foreach ($validdays as $dkey => $day) {

				if ($workhours) {					
					foreach ($workhours as $hours) {
						if ($hours->dateapplicable == $day) {
							$workhoursarray[$dkey] = $hours->hours_worked;
							break;
						}
					}
				}

				if ( !isset($workhoursarray[$dkey]) ) $workhoursarray[$dkey] = 0;
				
				$daylabels[] = date('D', strtotime($day));
			}
		
			$chart = "http://chart.apis.google.com/chart?chs=900x200&chds=0,8&cht=bvs&chco=0077CC&chbh=105&chd=t:".implode(',', $workhoursarray)."&chxt=x,y&chxl=0:|".implode('|', $daylabels)."|1:|0|1|2|3|4|5|6|7|8&chtt=Hours+Worked&chg=0,12.5";
			
			
			
			$work = $this->usersmodel->getUserWorkDone($user->id, $startdate);
		
			
			$this->view_data['chart'] = $chart;
			$this->view_data['updates'] = $work;
			$this->view_data['user'] = $user;

		
			$this->layout->buildPage('/users/viewstats', $this->view_data);
		} else redirect('');
	}


	public function modify($idField = 0) {
		$this->load->model('usersmodel');
		$this->load->helper('url');
		
		//$this->view_data['submenu']['Modify User'] = site_url('users/modify/'.$this->uri->segment(3));
		
		$submit = $this->input->post('Submit');
		
		if ( $submit != false ) {
			$data['user'] = $this->_get_form_values();
			
			if (strlen($data['user']->password)) $data['user']->password = md5($data['user']->password);
			else unset($data['user']->password);
			
			$this->usersmodel->modify($data['user']->id, (array)$data['user']);

			$this->db_session->set_flashdata('newid', $data['user']->id);
			$this->db_session->set_flashdata('flashmessage', 'The user was updated successfully.');
			
			redirect('/users/', 'location');
		} else {
			$this->load->model('costcentermodel');
			
			$this->view_data['user'] = $this->usersmodel->retrieve_by_pkey($idField);
			$this->view_data['action'] = 'modify';
			
			$departments = $this->costcentermodel->getAllCenters();
			
			$this->view_data['departments'] = $departments;
			
			$this->load->library('layout');
			$this->layout->buildPage('/users/usersdetails', $this->view_data);
		}
	}
	
	public function profile() {
		$this->load->model('usersmodel');
		$this->load->helper('url');
		
		$submit = $this->input->post('Submit');
		
		if ( $submit != false ) {
			$data = $this->_get_form_values('profile');
			
			$user = $this->usersmodel->retrieve_by_pkey($this->authentication->getUserId());
			
			if ($user->id != $data->id ) redirect('');
			
			if (strlen($data->password)) $data->password = md5($data->password);
			else unset($data->password);
			
			unset($data->active);
			unset($data->autoassign);
			unset($data->costcenterid);
			unset($data->profiletype);
			
			if ($data->notify_twitter && !$user->notify_twitter && $data->twitter_username && !$user->twitter_username) {
				//todo: allow twitter username / password setting in config
				//$this->load->library('twitter', array('username' => '', 'password' => ''));
				$this->twitter->updateDirect($data->twitter_username, 'You are now receiving notifications from epicentr.');
			}
			
			$this->usersmodel->modify($data->id, $data);

			$this->db_session->set_flashdata('newid', $data->id);
			$this->db_session->set_flashdata('flashmessage', 'The user was updated successfully.');
			
			redirect('/users/', 'location');
		} else {
			$user = $this->usersmodel->retrieve_by_pkey($this->authentication->getUserId());
			
			$user->notification_type = unserialize($user->notification_type);
			
			if (!is_array($user->notification_type)) $user->notification_type = array();
						
			$this->view_data['user'] = $user;
			$this->view_data['action'] = 'modify';
			
			$this->load->library('layout');
			$this->layout->buildPage('/users/profile', $this->view_data);
		}
	}

	public function delete() {
		$idField = $this->uri->segment(3);

		$this->load->model('usersmodel');
		$ok = $this->usersmodel->delete_by_pkey($idField);

		$this->load->helper('url');
		redirect('/users/', 'location');

	}
	
	public function deactivate($idField) {
		$this->load->model('usersmodel');
		$ok = $this->usersmodel->modify($idField, array('active' => 0) );
		redirect('users', 'location');
	}

	public function delete_ajax() {
		$this->load->model('usersmodel');

		$deleteItems = $this->input->post('delete');

		foreach ($deleteItems as $idField) {
			$data['deleted'] = 1;
			$this->usersmodel->modify($idField, $data);
		}
		echo 1; die();
	}

	public function undelete_ajax() {
		$this->load->model('usersmodel');

		$deleteItems = $this->input->post('delete');

		foreach ($deleteItems as $idField) {
			$data['deleted'] = 0;
			$this->usersmodel->modify($idField, $data);
		}
		echo 1; die();
	}
	
	private function _clear_form() {
		$data->id			= '';
		$data->username		= '';
		$data->password		= '';
		$data->emailaddress	= '';
		$data->firstname	= '';
		$data->lastname		= '';
		$data->profiletype	= '';
		$data->lastlogin	= '';
		$data->active		= 1;
		$data->autoassign	= 0;
		$data->datecreated	= '';
		$data->dateupdated	= '';
		$data->creator		= '';
		$data->updater		= '';

		return $data;

	}

	private function _get_form_values($action = null) {
		$data->id			= $this->input->post('id', TRUE);
		$data->username		= $this->input->post('username', TRUE);
		$data->password		= $this->input->post('password', TRUE);
		$data->emailaddress	= $this->input->post('emailaddress', TRUE);
		$data->firstname	= $this->input->post('firstname', TRUE);
		$data->lastname		= $this->input->post('lastname', TRUE);
		$data->profiletype	= $this->input->post('profiletype', TRUE);
		
		$data->costcenterid	= $this->input->post('costcenterid', TRUE);
		
		if ($action == 'profile') {
			
			if ( strlen($this->input->post('notify_twitter') ) ) $data->notify_twitter = 1;
			else $data->notify_twitter = 0;
			
			$data->twitter_username = $this->input->post('twitter_username');
			
			if ( strlen($this->input->post('notify_email') ) ) $data->notify_email = 1;
			else $data->notify_email = 0;
			
			$data->notification_type = serialize($this->input->post('notification_type'));
			
			$data->openid_identifier	= $this->input->post('openid_identifier', TRUE);
		}

		$data->active		= $this->input->post('active', TRUE);
		$data->autoassign	= $this->input->post('autoassign', TRUE);
		
		if ( $action == 'add') {
			$data->datecreated = date('Y-m-d H:i:s');
			$data->creatorid = $this->authentication->getUserId();
		} else {
			$data->dateupdated = date('Y-m-d H:i:s');
			$data->updaterid = $this->authentication->getUserId();
		}

		return $data;
	}
	
	function day_range($sd,$ed)
	{
	$tmp = array();
	$sdu = strtotime($sd);
	$edu = strtotime($ed);
	while ($sdu <= $edu) {
	$tmp[] = date('Y-m-d',$sdu);
	$sdu = strtotime('+1 day',$sdu);
	}
	return ($tmp);
	}

}
?>